<template>
    <div class="crm-invoice-container">
        <el-dialog title="新增发票" v-model="isShowDialog" :close-on-click-modal="false">
            <el-form ref="addCrmInvoiceFormRef" :model="formData" :rules="formRules" label-width="120px">
                <el-row :gutter="35">
                    <el-col>
                        <el-form-item label="发票文件" prop="attachments">
                            <Storage :model="attachment" @success="onUploadSuccess" @remove="onUploadRemove"></Storage>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="关联合同" prop="contractId">
                            <el-select v-model="formData.contractId" filterable remote 
                                @change="handContractChange"
                                @click="loadContractData()"
                                :remote-method="loadContractData" placeholder="请选择关联合同" clearable class="w100">
								<el-option 
									v-for="item in contracts"
									:key="item.id"
									:label="`（${item.contractCode}）${item.contractName}`"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="收支类型" prop="invoiceFlag">
                            <Dictionary v-model="formData.invoiceFlag" dict-label="crm_invoice_flag" placeholder="请选择发票收支类型"></Dictionary>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="发票类型" prop="invoiceType">
                            <Dictionary v-model="formData.invoiceType" dict-label="crm_invoice_type" placeholder="请输入发票类型"></Dictionary>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="发票代码" prop="invoiceCode">
                            <el-input v-model="formData.invoiceCode" placeholder="请输入发票代码" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="发票号码" prop="invoiceNumber">
                            <el-input v-model="formData.invoiceNumber" placeholder="请输入发票号码" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="发票金额" prop="invoiceAmount">
                            <el-input-number v-model="formData.invoiceAmount" :min="0" placeholder="请输入发票金额（单位：元）" clearable class="w100"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="开票日期" prop="invoiceDate">
                            <el-date-picker v-model="formData.invoiceDate" placeholder="请输入开票日期" value-format="YYYY-MM-DD" clearable class="w100"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="抬头类型" prop="invoiceTitleType">
                            <Dictionary v-model="formData.invoiceTitleType" dict-label="crm_invoice_title" placeholder="请输入抬头类型"></Dictionary>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="开票抬头" prop="invoiceTitle">
                            <el-input v-model="formData.invoiceTitle" placeholder="请输入开票抬头" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="购方纳税识别号" prop="buyerTaxNumber">
                            <el-input v-model="formData.buyerTaxNumber" placeholder="请输入购方纳税识别号" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="销方纳税识别号" prop="sellerTaxNumber">
                            <el-input v-model="formData.sellerTaxNumber" placeholder="请输入纳税识别号" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="购方开户行" prop="buyerDepositBank">
                            <el-input v-model="formData.buyerDepositBank" placeholder="请输入购方开户行" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="销方开户行" prop="sellerDepositBank">
                            <el-input v-model="formData.sellerDepositBank" placeholder="请输入销方开户行" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="购方开户账户" prop="buyerDepositAccount">
                            <el-input v-model="formData.buyerDepositAccount" placeholder="请输入购方开户账户" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="销方开户账户" prop="sellerDepositAccount">
                            <el-input v-model="formData.sellerDepositAccount" placeholder="请输入销方开户账户" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="购方开户地址" prop="buyerDepositAddress">
                            <el-input v-model="formData.buyerDepositAddress" placeholder="请输入购方开户地址" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="销方开户地址" prop="sellerDepositAddress">
                            <el-input v-model="formData.sellerDepositAddress" placeholder="请输入销方开户地址" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="购方联系电话" prop="buyerTelephone">
                            <el-input v-model="formData.buyerTelephone" placeholder="请输入购方联系电话" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="销方联系电话" prop="sellerTelephone">
                            <el-input v-model="formData.sellerTelephone" placeholder="请输入销方联系电话" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onCancel">取 消</el-button>
                    <el-button type="primary" @click="onSubmit">保 存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getCrmContractList } from '/@/api/crm/contract/index';
import { addCrmInvoice } from '/@/api/crm/invoice/index';
import Dictionary from '/@/components/dictionary/index.vue';
import Storage from '/@/views/crm/components/storage/index.vue';
export default {
    name: 'crm/invoice/add',
    components: { Dictionary, Storage },
    setup(props, context) {
        const validAttachmentNotEmpty = (rule, value, callback) => {
            const { attachments } = state.formData;
            if(attachments == undefined || attachments.length == 0){
                return callback(new Error('发票文件不能为空'));
            }else{
                return callback();
            }
        }
        const addCrmInvoiceFormRef = ref();
        const state = reactive({
            isShowDialog: false,
            contracts: [],
            attachment: {
                upload:{
                    limit: 1,
                    accept: '.jpg,.png,.svg,.webp,.gif,.pdf',
                    images: []
                }
            },
            formData: {
                attachments: [],
            },
            formRules : {
                //attachment: { validator: validAttachmentNotEmpty, trigger: 'blur' },
                contractId: { required: true, message: '关联合同不能为空', trigger: 'blur' },
                invoiceFlag: { required: true, message: '发票收支类型不能为空', trigger: 'blur' },
                invoiceType: { required: true, message: '发票类型不能为空', trigger: 'blur' },
                invoiceAmount: { required: true, message: '发票金额不能为空', trigger: 'blur' },
                invoiceDate: { required: true, message: '开票日期不能为空', trigger: 'blur' },
                invoiceTitleType: { required: true, message: '抬头类型不能为空', trigger: 'blur' },
                invoiceTitle: { required: true, message: '开票抬头不能为空', trigger: 'blur' },
            }
        });

        // 加载合同数据
        const loadContractData = (query?: string) => {
            if(query == '') return;
            getCrmContractList({contractName: query, examineStatus: '2'}).then((res) => {
                if(res.code == 0){
                    state.contracts = res.data;
                }
            });
        };
        // 选择合同
        const handContractChange = (contractId) => {
            const contract = state.contracts.find(item => item.id == contractId);
            state.formData.contractId = contract?.id;
            state.formData.contractName = contract?.contractName;
        };

        const onUploadSuccess = (file, urls) => {
            state.formData?.attachments.push({url: file.url, name: file.name});
        };

        const onUploadRemove = (file, urls) => {
            const index = state.formData?.attachments.findIndex((item) => item.url == file.url);
            if(index > -1){
				state.formData?.attachments.splice(index, 1);
			}
        };

        // 打开弹窗
        const openDialog = (row?: object) => {
            state.isShowDialog = true;
        };
        // 关闭弹窗
        const closeDialog = (row?: object) => {
            state.isShowDialog = false;
            for(var key in state.formData) {
                state.formData[key] = undefined;
            }
            addCrmInvoiceFormRef.value.resetFields();
        };
        // 取消
        const onCancel = () => {
            closeDialog();
        };
        // 新增
        const onSubmit = () => {
            addCrmInvoiceFormRef.value.validate(valid => {
                if(valid){
                    let params = {
                        attachments: state.formData.attachments,
                        contractId: state.formData.contractId,
                        invoiceFlag: state.formData.invoiceFlag,
                        invoiceCode: state.formData.invoiceCode,
                        invoiceNumber: state.formData.invoiceNumber,
                        invoiceAmount: state.formData.invoiceAmount,
                        invoiceDate: state.formData.invoiceDate,
                        invoiceType: state.formData.invoiceType,
                        invoiceTitleType: state.formData.invoiceTitleType,
                        invoiceTitle: state.formData.invoiceTitle,
                        buyerDepositBank: state.formData.buyerDepositBank,
                        buyerDepositAccount: state.formData.buyerDepositAccount,
                        buyerTaxNumber: state.formData.buyerTaxNumber,
                        buyerDepositAddress: state.formData.buyerDepositAddress,
                        buyerTelephone: state.formData.buyerTelephone,
                        sellerDepositBank: state.formData.sellerDepositBank,
                        sellerDepositAccount: state.formData.sellerDepositAccount,
                        sellerDepositAddress: state.formData.sellerDepositAddress,
                        sellerTaxNumber: state.formData.sellerTaxNumber,
                        sellerTelephone: state.formData.sellerTelephone,
                        remark: state.formData.remark,
                    }
                    addCrmInvoice(params).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('保存成功');
                            context.emit('submit');
                            closeDialog();
                        }
                    });
                }
            });
        };
        return {
            addCrmInvoiceFormRef,
            openDialog,
            closeDialog,
            onCancel,
            onSubmit,
            loadContractData,
            handContractChange,
            onUploadSuccess,
            onUploadRemove,
            ...toRefs(state),
        };
    },
};
</script>